<template>
  <div class="app-container">
    <router-link to="product/create">
      <el-button id="create_page" type="success" size="small"><i class="el-icon-plus" /> 新增商品</el-button>
    </router-link>
    <el-button class="delete_button" type="warning" size="small" @click="handleDeleteMultiple"><i
      class="el-icon-delete"
    /> 批量删除
    </el-button>
    <el-button
      :loading="downloadLoading"
      style="margin-left: 5px"
      type="primary"
      size="small"
      icon="el-icon-document"
      @click="handleDownload"
    >
      导出商品
    </el-button>

    <el-row>
      <el-col class="name_s">
        <el-form :inline="true" :model="searchData">
          <el-form-item>
            <el-input v-model="searchData.keyword" size="medium" placeholder="商品名" clearable @clear="init" />
          </el-form-item>

          <el-form-item>
            <el-select v-model="searchData.categoryId" filterable placeholder="所有分类">
              <el-option-group
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
              >
                <el-option
                  v-for="child in category.children"
                  :key="child.id"
                  :label="child.name"
                  :value="child.id"
                />
              </el-option-group>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select v-model="searchData.brandId" filterable placeholder="所有品牌">
              <el-option
                v-for="brand in brands"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-checkbox-button v-model="searchData.discount" size="medium">特惠药品</el-checkbox-button>
            <el-checkbox-button v-model="searchData.emergency" size="medium">应急储备</el-checkbox-button>
            <el-checkbox-button v-model="searchData.nourishing" size="medium">营养滋补</el-checkbox-button>
            <el-checkbox-button v-model="searchData.prevention" size="medium">防疫专区</el-checkbox-button>
            <el-checkbox-button v-model="searchData.commonUse" size="medium">家中常备</el-checkbox-button>
            <el-checkbox-button v-model="searchData.cardiovascular" size="medium">心脑血管</el-checkbox-button>
          </el-form-item>

          <el-form-item>
            <el-date-picker
              v-model="searchData.createdAt"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="warning" size="medium" icon="el-icon-search" @click="handerSearch">搜索
            </el-button>
            <el-button
              class="reset"
              type="info"
              size="medium"
              icon="el-icon-refresh-left"
              native-type="reset"
              @click="handerReset"
            >重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-card class="table_style">
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="products"
        element-loading-text="Loading"
        style="width: 100%"
        border
        stripe
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <el-table-column label="ID" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="缩略图">
          <template slot-scope="scope">
            <img :src="scope.row.image" alt="" class="thumb">
          </template>
        </el-table-column>
        <el-table-column label="商品名称">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属分类">
          <template slot-scope="scope">
            <span>{{ scope.row.category.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属品牌">
          <template slot-scope="scope">
            <span>{{ scope.row.brand.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.tags.length === 0" type="danger">暂无标签</el-tag>
            <el-tag v-else type="warning">{{ scope.row.tags | tagFormat }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="单价">
          <template slot-scope="scope">
            <span>{{ scope.row.price }} 元</span>
          </template>
        </el-table-column>
        <el-table-column label="推荐药品">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.recommend" @change="changeAttr(scope.row,'recommend')" />
          </template>
        </el-table-column>
        <el-table-column label="特惠药品">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.discount"
              active-color="#303133"
              @change="changeAttr(scope.row,'discount')"
            />
          </template>
        </el-table-column>
        <el-table-column label="应急储备">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.emergency"
              active-color="#F56C6C"
              @change="changeAttr(scope.row,'emergency')"
            />
          </template>
        </el-table-column>
        <el-table-column label="营养滋补">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.nourishing"
              active-color="#1f99b0"
              @change="changeAttr(scope.row,'nourishing')"
            />
          </template>
        </el-table-column>
        <el-table-column label="防疫专区">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.prevention"
              active-color="#563d7c"
              @change="changeAttr(scope.row,'prevention')"
            />
          </template>
        </el-table-column>
        <el-table-column label="家中常备">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.commonUse"
              active-color="#909399"
              @change="changeAttr(scope.row,'commonUse')"
            />
          </template>
        </el-table-column>
        <el-table-column label="心脑血管">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.cardiovascular"
              active-color="#e6a23c"
              @change="changeAttr(scope.row,'cardiovascular')"
            />
          </template>
        </el-table-column>
        <el-table-column label="是否上架">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.onsale"
              active-color="#13ce66"
              @change="changeAttr(scope.row,'onsale')"
            />
          </template>
        </el-table-column>
        <el-table-column label="库存">
          <template slot-scope="scope">
            <span>{{ scope.row.stock }}</span>
          </template>
        </el-table-column>
        <el-table-column label="销量">
          <template slot-scope="scope">
            <span>{{ scope.row.sale }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建日期">
          <template slot-scope="scope">
            <span>{{ scope.row.createdAt|sub_date }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="查看详情" placement="top" enterable>
              <el-button
                size="mini"
                type="success"
                icon="el-icon-star-off"
                @click="dialogShow(scope.row)"
              />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="编辑商品" placement="top" enterable>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(scope.row)"
              />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除商品" placement="top" enterable>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="footer_page"
        background
        layout="total, prev, pager, next, jumper"
        :total="page.total"
        :page-size="page.pageSize"
        hide-on-single-page
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!--详细信息-->
    <el-dialog title="详细信息" :visible.sync="dialogTableVisible">
      <el-form :model="product">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="product.name" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="生产厂家" :label-width="formLabelWidth">
          <el-input v-model="product.factory" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="规格" :label-width="formLabelWidth">
          <el-input v-model="product.specs" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="计量单位" :label-width="formLabelWidth">
          <el-input v-model="product.unit" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="批准文号" :label-width="formLabelWidth">
          <el-input v-model="product.approval_number" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="商标" :label-width="formLabelWidth">
          <el-input v-model="product.trademark" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="产地" :label-width="formLabelWidth">
          <el-input v-model="product.place_of_origin" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="类别" :label-width="formLabelWidth">
          <el-input v-model="product.drug" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="有效期" :label-width="formLabelWidth">
          <el-input v-model="product.expiry_date" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="温馨提示" :label-width="formLabelWidth">
          <el-input v-model="product.reminder" type="textarea" :rows="4" disabled />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { fetchCategoryList } from '@/api/category'
import { fetchBrandList } from '@/api/brand'
import { changeProductAttr, deleteMultipleProduct, deleteProduct, fetchProduct, fetchProductList } from '@/api/product'

export default {
  filters: {
    // 拆分标签名
    tagFormat(value) {
      const t = value.map((item) => {
        return item.name
      })
      return t.join(', ')
    },
    // 日期截取
    sub_date: function(val) {
      return val.substring(0, 10)
    }
  },
  data() {
    return {
      products: [],
      categories: [],
      brands: [],
      listLoading: true,
      downloadLoading: false,
      searchData: {
        keyword: '',
        categoryId: '',
        brandId: '',
        discount: '',
        emergency: '',
        nourishing: '',
        prevention: '',
        commonUse: '',
        cardiovascular: '',
        createdAt: ''
      },
      page: {
        total: 0,
        current_page: 1, // 当前页数
        pageSize: 0 // 每页显示多少条数据
      },
      dialogTableVisible: false,
      formLabelWidth: '120px',
      product: {},
      multipleSelection: []
    }
  },
  created() {
    // 所有分类
    fetchCategoryList().then((res) => {
      this.categories = res.data.categories
    })
    // 所有品牌
    fetchBrandList().then((res) => {
      this.brands = res.data.brands
    })
    this.init()
  },
  methods: {
    init() {
      this.listLoading = true
      // 定义搜索参数
      const params = {
        name: this.searchData.keyword,
        categoryId: this.searchData.categoryId,
        brandId: this.searchData.brandId,
        discount: this.searchData.discount,
        emergency: this.searchData.emergency,
        nourishing: this.searchData.nourishing,
        prevention: this.searchData.prevention,
        commonUse: this.searchData.commonUse,
        cardiovascular: this.searchData.cardiovascular,
        createdAt: this.searchData.createdAt,
        currentPage: this.page.current_page
      }
      // 所有商品
      fetchProductList(params).then((res) => {
        // console.log(res)
        this.products = res.data.products
        this.page = {
          total: res.data.pagination.total,
          pageSize: parseInt(res.data.pagination.pageSize),
          current_page: parseInt(res.data.pagination.current_page)
        }
        this.listLoading = false
      })
    },
    handerSearch() {
      this.init()
    },
    // 搜索后重置搜索内容
    handerReset() {
      this.searchData = {
        keyword: '',
        categoryId: '',
        discount: '',
        emergency: '',
        nourishing: '',
        prevention: '',
        commonUse: '',
        cardiovascular: '',
        createdAt: ''
      }
      this.init()
    },
    handleCurrentChange(val) {
      this.page.current_page = val
      this.init()
    },
    // 显示商品详情
    dialogShow(row) {
      this.dialogTableVisible = true
      fetchProduct(row.id).then((res) => {
        this.product = res.data.product
      })
    },
    // 点击跳转到编辑页面
    handleEdit(row) {
      this.$router.push({
        name: 'ProductEdit',
        params: { id: row.id }
      })
    },
    // 删除单个商品
    handleDelete(row) {
      this.$confirm('删除该商品后，对应的标签和相册将被删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        deleteProduct(row.id).then((res) => {
          this.init()
          this.$message({
            type: 'success',
            message: res.message
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 全选、反选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 批量删除商品
    handleDeleteMultiple() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('您至少要选中一条数据~')
      } else {
        this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          const checkedId = this.multipleSelection.map((item) => {
            return item.id
          })
          deleteMultipleProduct({ checked_id: checkedId }).then((res) => {
            this.init()
            this.$message({
              type: 'success',
              message: res.message
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    // 改变属性
    changeAttr(row, type) {
      changeProductAttr(row.id, { type: type }).then((res) => {
        if (res.code === 20000) return this.$message.success(res.message)
        return this.$message.error(res.message)
      })
    },
    // 导出商品
    handleDownload() {
      this.downloadLoading = true
      this.$confirm('确定要导出该商品吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        import('@/vendor/Export2Excel').then(excel => {
          // 列头
          const tHeader = ['商品ID', '商品名称', '商品分类', '商品品牌', '单价', '推荐药品', '特惠药品', '应急储备', '营养滋补', '防疫专区', '家中常备', '心脑血管', '是否上架', '库存', '销量', '生产厂家', '规格', '批准文号', '创建时间']
          const filterVal = ['id', 'name', 'category', 'brand', 'price', 'recommend', 'discount', 'emergency', 'nourishing', 'prevention', 'commonUse', 'cardiovascular', 'onsale', 'stock', 'sale', 'factory', 'specs', 'approval_number', 'createdAt']
          const products = this.products
          const data = this.formatJson(filterVal, products)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '商品列表',
            autoWidth: true,
            bookType: 'xlsx'
          })
          this.$message.success('导出成功')
          this.init()
          this.downloadLoading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        // 组装数据
        if (j === 'createdAt') {
          return this.$moment(v[j]).utcOffset('+0800').format('YYYY-MM-DD HH:mm:ss')
        } else if (j === 'recommend') {
          // eslint-disable-next-line no-return-assign
          return v[j] = v[j] ? '是' : '否'
        } else if (j === 'discount') {
          // eslint-disable-next-line no-return-assign
          return v[j] = v[j] ? '是' : '否'
        } else if (j === 'emergency') {
          // eslint-disable-next-line no-return-assign
          return v[j] = v[j] ? '是' : '否'
        } else if (j === 'nourishing') {
          // eslint-disable-next-line no-return-assign
          return v[j] = v[j] ? '是' : '否'
        } else if (j === 'prevention') {
          // eslint-disable-next-line no-return-assign
          return v[j] = v[j] ? '是' : '否'
        } else if (j === 'commonUse') {
          // eslint-disable-next-line no-return-assign
          return v[j] = v[j] ? '是' : '否'
        } else if (j === 'cardiovascular') {
          // eslint-disable-next-line no-return-assign
          return v[j] = v[j] ? '是' : '否'
        } else if (j === 'onsale') {
          // eslint-disable-next-line no-return-assign
          return v[j] = v[j] ? '是' : '否'
        } else if (j === 'category') {
          // eslint-disable-next-line no-return-assign
          return v[j] = v[j].name
        } else if (j === 'brand') {
          // eslint-disable-next-line no-return-assign
          return v[j] = v[j].name
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style scoped>
.reset {
  margin-left: 5px;
}

.footer_page {
  margin-top: 20px;
}

.name_s {
  margin-top: 15px;
}

.delete_button {
  margin-left: 5px;
}

.thumb {
  width: 80px;
  height: 60px;
}
</style>
